package com.onlinelearn.paymentservice.service;

import com.onlinelearn.paymentservice.model.PaymentOrder;
import com.onlinelearn.paymentservice.model.PaymentOrderStatus;
import com.onlinelearn.paymentservice.repository.PaymentOrderRepository;
import com.onlinelearn.paymentservice.exception.PaymentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

@Service
public class RefundService {
    private static final Logger logger = LoggerFactory.getLogger(RefundService.class);

    @Autowired
    private PaymentOrderRepository orderRepository;

    @Autowired
    private PaymentGatewayService paymentGateway;

    @Transactional
    public RefundResult processRefund(Long orderId, RefundReason reason) {
        PaymentOrder order = orderRepository.findById(orderId)
            .orElseThrow(() -> new PaymentException(
                "订单未找到", 
                PaymentException.ErrorCode.ORDER_NOT_FOUND
            ));

        validateRefundEligibility(order, reason);

        try {
            RefundResult refundResult = paymentGateway.processRefund(order);

            if (refundResult.isSuccess()) {
                order.setStatus(PaymentOrderStatus.REFUNDED);
                order.setRefundTime(LocalDateTime.now());
                order.setRefundReason(reason);
                orderRepository.save(order);

                logger.info("订单 {} 退款成功", orderId);
                return refundResult;
            } else {
                logger.error("订单 {} 退款失败: {}", orderId, refundResult.getErrorMessage());
                throw new PaymentException(
                    "退款处理失败: " + refundResult.getErrorMessage(), 
                    PaymentException.ErrorCode.REFUND_NOT_ALLOWED
                );
            }
        } catch (Exception e) {
            logger.error("退款处理异常", e);
            throw new PaymentException(
                "退款处理异常: " + e.getMessage(), 
                PaymentException.ErrorCode.REFUND_NOT_ALLOWED
            );
        }
    }

    private void validateRefundEligibility(PaymentOrder order, RefundReason reason) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime paymentTime = order.getPaymentTime();

        // 检查退款时间
        if (ChronoUnit.DAYS.between(paymentTime, now) > 7) {
            throw new PaymentException(
                "已超过7天退款期限", 
                PaymentException.ErrorCode.REFUND_NOT_ALLOWED
            );
        }

        // 检查订单状态
        if (order.getStatus() != PaymentOrderStatus.PAID) {
            throw new PaymentException(
                "订单状态不允许退款", 
                PaymentException.ErrorCode.INVALID_ORDER_STATUS
            );
        }
    }
}

// 退款结果类
class RefundResult {
    private boolean success;
    private String refundId;
    private String errorMessage;

    private RefundResult(boolean success, String refundId, String errorMessage) {
        this.success = success;
        this.refundId = refundId;
        this.errorMessage = errorMessage;
    }

    public static RefundResult success(String refundId) {
        return new RefundResult(true, refundId, null);
    }

    public static RefundResult failed(String errorMessage) {
        return new RefundResult(false, null, errorMessage);
    }

    // Getters
    public boolean isSuccess() {
        return success;
    }
}

// 退款原因枚举
enum RefundReason {
    COURSE_NOT_MEET_EXPECTATION,
    TECHNICAL_ISSUES,
    PERSONAL_REASON,
    OTHER
} 